package com.effectiv.crm.i18n;

import java.text.MessageFormat;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;

import org.springframework.context.MessageSource;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import com.effectiv.crm.domain.I18nMessage;
import com.effectiv.crm.service.api.I18nMessageService;

@Slf4j
@Named("messageSource")
public class DatabaseDrivenMessageResource extends AbstractMessageSource implements ResourceLoaderAware{
	
	@Inject
	@Named("propertiesMessageSource")
	private MessageSource parent;
	
	private ResourceLoader resourceLoader;
	
	@Inject
	private I18nMessageService service;
	
	@Override
    protected MessageFormat resolveCode(String code, Locale locale) {
        String msg = getText(code, locale);
        MessageFormat result = createMessageFormat(msg, locale);
        return result;
    }
 
    @Override
    protected String resolveCodeWithoutArguments(String code, Locale locale) {
        return getText(code, locale);
    }
 
    private String getText(String code, Locale locale) {
    	log.info("Resolving message with code - {} , locale - {}", code, locale);
    	I18nMessage localized = service.findByKeyAndLocale(code, locale);
    	String textForCurrentLanguage = null;
        
        if (localized==null) {
            //Check parent message
            logger.info("Fallback to properties message");
            try {
                textForCurrentLanguage = getParentMessageSource().getMessage(code, null, locale);
            } catch (Exception e) {
                logger.info("Cannot find message with code: " + code);
            }
        }
        else{
        	 textForCurrentLanguage = localized.getValue();
        }
        return textForCurrentLanguage != null ? textForCurrentLanguage : code;
    }
	

	@PostConstruct
	public void init() {
		super.setParentMessageSource(parent);
	}

	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
	}
}
